<template>
  <div class="class-space-container">
    <el-card class="class-space-card">
      <template #header>
        <div class="card-header">
          <h2>班级空间</h2>
          <div class="class-info" v-if="classInfo">
            <el-tag size="large" effect="plain">班级ID: {{ classInfo.classId }}</el-tag>
            <el-tag size="large" effect="plain" type="success">班级名称: {{ classInfo.className }}</el-tag>
          </div>
          <div class="header-actions">
            <el-select 
              v-model="priorityFilter" 
              placeholder="消息筛选" 
              clearable 
              @change="filterMessages"
              size="small"
              style="width: 120px;"
            >
              <el-option label="全部消息" :value="null" />
              <el-option label="普通消息" :value="0" />
              <el-option label="紧急消息" :value="1" />
              <el-option label="严重消息" :value="2" />
            </el-select>
            <el-button v-if="isTeacher" type="primary" @click="openSendMessageDialog">
              <el-icon><el-icon-plus /></el-icon>发送新消息
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="class-messages" v-loading="loading">
        <div v-if="!loading && filteredMessages.length === 0" class="empty-state">
          <el-empty description="暂无班级消息" />
        </div>
        
        <el-timeline v-else>
          <el-timeline-item
            v-for="message in filteredMessages"
            :key="message.id"
            :timestamp="formatTime(message.sendTime)"
            :type="getPriorityType(message.priority)"
            :hollow="message.priority === 0"
          >
            <el-card class="message-card" :class="getPriorityClass(message.priority)">
              <template #header>
                <div class="message-header">
                  <div class="message-title">
                    <span class="message-from">来自: {{ message.teacherName }}</span>
                    <el-tag 
                      size="small" 
                      :type="getPriorityTagType(message.priority)"
                    >
                      {{ getPriorityLabel(message.priority) }}
                    </el-tag>
                  </div>
                  <div class="message-actions">
                    <el-tag v-if="!isTeacher && message.submitted" type="success" size="small">已提交</el-tag>
                    <el-button 
                      v-if="!isTeacher && !message.submitted" 
                      type="primary" 
                      size="small" 
                      @click="submitTask(message.id)"
                    >
                      提交任务
                    </el-button>
                    <el-button 
                      v-if="isTeacher" 
                      type="danger" 
                      size="small" 
                      @click="deleteMessage(message.id)"
                      :icon="Delete"
                      circle
                      plain
                    ></el-button>
                  </div>
                </div>
              </template>
              
              <div class="message-content">
                {{ message.content }}
              </div>
              
              <div v-if="message.problemIds && message.problemIds.length > 0" class="message-problems">
                <div class="problems-title">相关题目:</div>
                <div class="problems-list">
                  <el-tag 
                    v-for="problemId in message.problemIds" 
                    :key="problemId"
                    effect="plain"
                    class="problem-tag"
                    @click="navigateToProblem(problemId)"
                  >
                    题目#{{ problemId }}
                  </el-tag>
                </div>
              </div>
              
              <div class="task-status" v-if="isTeacher && message.submittedCount !== undefined">
                <div class="status-info">
                  <span>任务提交状态: </span>
                  <el-progress 
                    :percentage="calculateSubmissionPercentage(message)" 
                    :stroke-width="12"
                    :format="percentageFormat"
                  ></el-progress>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
    
    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="发送班级消息"
      width="500px"
    >
      <el-form 
        ref="formRef" 
        :model="messageForm" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model.number="messageForm.classId" placeholder="请输入班级ID" />
        </el-form-item>
        
        <el-form-item label="消息内容" prop="content">
          <el-input 
            v-model="messageForm.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入消息内容"
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="messageForm.priority" placeholder="请选择优先级">
            <el-option :value="0" label="普通消息" />
            <el-option :value="1" label="紧急消息" />
            <el-option :value="2" label="严重消息" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="相关题目">
          <el-select
            v-model="selectedProblems"
            multiple
            filterable
            placeholder="请选择相关题目ID (可选)"
          >
            <el-option
              v-for="id in availableProblems"
              :key="id"
              :label="`题目 #${id}`"
              :value="id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设置截止时间" prop="deadlineEnabled">
          <el-switch v-model="messageForm.deadlineEnabled" />
          <el-date-picker
            v-if="messageForm.deadlineEnabled"
            v-model="messageForm.deadline"
            type="datetime"
            placeholder="选择截止日期和时间"
            style="margin-left: 10px; width: 220px;"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sendMessage" :loading="sending">
            发送
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { useUserStore } from '../store/user';
import { getClassMessages, sendClassMessage, commitTask } from '../api/class';
import { fetchProblemList } from '../api/problem';

// 定义类型
interface ClassMessage {
  id: number;
  teacherId: number;
  teacherName: string;
  classId: number;
  content: string;
  sendTime: string;
  priority: number;
  problemIds?: number[];
  submitted: boolean;
  submittedCount?: number;
  totalStudents?: number;
}

interface ClassInfo {
  classId: number;
  className: string;
  studentCount: number;
}

// 图标组件
const ElIconPlus = Plus;

// 路由
const router = useRouter();
const userStore = useUserStore();

// 数据状态
const loading = ref(false);
const messages = ref<ClassMessage[]>([]);
const dialogVisible = ref(false);
const sending = ref(false);
const formRef = ref();
const availableProblems = ref<number[]>([]);
const priorityFilter = ref<number | null>(null);

// 班级信息
const classInfo = ref<ClassInfo>({
  classId: Number(userStore.userInfo?.classId) || 0,
  className: '默认班级',
  studentCount: 0
});

// 筛选后的消息
const filteredMessages = computed(() => {
  if (priorityFilter.value === null) {
    return messages.value;
  }
  return messages.value.filter(msg => msg.priority === priorityFilter.value);
});

// 判断是否是教师
const isTeacher = computed(() => {
  const role = userStore.userInfo?.role;
  return role === '1' || role === 1;
});

// 表单数据
const messageForm = reactive({
  classId: Number(userStore.userInfo?.classId) || '',
  content: '',
  priority: 0,
  deadlineEnabled: false,
  deadline: null as Date | null
});

// 已选择的题目ID
const selectedProblems = ref<number[]>([]);

// 表单验证规则
const rules = {
  classId: [
    { required: true, message: '请输入班级ID', trigger: 'blur' },
    { type: 'number', message: '班级ID必须是数字', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 2, max: 500, message: '消息内容长度应在2到500个字符之间', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
};

// 获取班级消息
const fetchClassMessages = async () => {
  loading.value = true;
  try {
    const result = await getClassMessages();
    if (result && Array.isArray(result)) {
      messages.value = result.map((msg: any) => ({
        ...msg,
        submitted: false, // 假设初始状态都是未提交的
        submittedCount: isTeacher.value ? Math.floor(Math.random() * 30) : undefined, // 模拟数据，实际应从后端获取
        totalStudents: isTeacher.value ? 30 : undefined // 模拟数据，实际应从后端获取
      }));
    } else if (result && result.data && Array.isArray(result.data)) {
      messages.value = result.data.map((msg: any) => ({
        ...msg,
        submitted: false,
        submittedCount: isTeacher.value ? Math.floor(Math.random() * 30) : undefined,
        totalStudents: isTeacher.value ? 30 : undefined
      }));
    } else {
      messages.value = [];
    }
  } catch (error) {
    console.error('获取班级消息失败:', error);
    ElMessage.error('获取班级消息失败');
  } finally {
    loading.value = false;
  }
};

// 获取题目列表
const fetchProblems = async () => {
  try {
    const result = await fetchProblemList({
      pageNum: 1,
      pageSize: 100,
      sortBy: 'id',
      orderBy: 'asc'
    });
    if (result && result.data && result.data.records) {
      availableProblems.value = result.data.records.map((problem: any) => problem.id);
    }
  } catch (error) {
    console.error('获取题目列表失败:', error);
  }
};

// 筛选消息
const filterMessages = () => {
  // 筛选逻辑已通过计算属性实现
};

// 计算提交百分比
const calculateSubmissionPercentage = (message: ClassMessage) => {
  if (!message.submittedCount || !message.totalStudents) return 0;
  return Math.round((message.submittedCount / message.totalStudents) * 100);
};

// 格式化百分比显示
const percentageFormat = (percentage: number) => {
  if (percentage === 100) return '已全部提交';
  return `${percentage}%`;
};

// 打开发送消息对话框
const openSendMessageDialog = () => {
  dialogVisible.value = true;
  // 重置表单
  messageForm.content = '';
  messageForm.priority = 0;
  messageForm.deadlineEnabled = false;
  messageForm.deadline = null;
  selectedProblems.value = [];
};

// 发送消息
const sendMessage = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      sending.value = true;
      try {
        // 构建消息对象
        const message = {
          teacherId: userStore.userInfo?.id || 0,
          teacherName: userStore.userInfo?.username || '未知教师',
          classId: messageForm.classId,
          content: messageForm.content,
          priority: messageForm.priority,
          deadline: messageForm.deadlineEnabled ? messageForm.deadline : null
        };
        
        // 发送消息
        await sendClassMessage(message, selectedProblems.value.length > 0 ? selectedProblems.value : undefined);
        
        ElMessage.success('消息发送成功');
        dialogVisible.value = false;
        
        // 重新获取消息列表
        fetchClassMessages();
      } catch (error) {
        console.error('发送消息失败:', error);
        ElMessage.error('发送消息失败，请检查网络或权限');
      } finally {
        sending.value = false;
      }
    }
  });
};

// 提交任务
const submitTask = async (messageId: number) => {
  try {
    await ElMessageBox.confirm('确定要提交此任务吗？提交后将无法撤销', '提交确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await commitTask(messageId);
    ElMessage.success('任务提交成功');
    
    // 更新消息状态
    const index = messages.value.findIndex(msg => msg.id === messageId);
    if (index !== -1) {
      messages.value[index].submitted = true;
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交任务失败:', error);
      ElMessage.error('提交任务失败');
    }
  }
};

// 删除消息
const deleteMessage = async (messageId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除此消息吗？删除后将无法恢复', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    // 这里应该调用删除消息的API
    // await deleteClassMessage(messageId);
    ElMessage.success('消息删除成功');
    
    // 更新消息列表
    messages.value = messages.value.filter(msg => msg.id !== messageId);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error);
      ElMessage.error('删除消息失败');
    }
  }
};

// 跳转到题目详情
const navigateToProblem = (problemId: number) => {
  router.push(`/problem/${problemId}`);
};

// 格式化优先级
const getPriorityLabel = (priority: number) => {
  switch (priority) {
    case 0: return '普通消息';
    case 1: return '紧急消息';
    case 2: return '严重消息';
    default: return '普通消息';
  }
};

// 获取优先级对应的标签类型
const getPriorityTagType = (priority: number) => {
  switch (priority) {
    case 0: return 'info';
    case 1: return 'warning';
    case 2: return 'danger';
    default: return 'info';
  }
};

// 获取优先级对应的时间线类型
const getPriorityType = (priority: number) => {
  switch (priority) {
    case 0: return '';
    case 1: return 'warning';
    case 2: return 'danger';
    default: return '';
  }
};

// 获取优先级对应的消息卡片类名
const getPriorityClass = (priority: number) => {
  switch (priority) {
    case 0: return 'normal-message';
    case 1: return 'warning-message';
    case 2: return 'danger-message';
    default: return '';
  }
};

// 格式化时间
const formatTime = (timeString: string) => {
  if (!timeString) return '';
  
  try {
    const date = new Date(timeString);
    return date.toLocaleString();
  } catch (error) {
    return timeString;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchClassMessages();
  if (isTeacher.value) {
    fetchProblems();
  }
});
</script>

<style scoped lang="scss">
.class-space-container {
  padding: 20px;
  
  .class-space-card {
    max-width: 1000px;
    margin: 0 auto;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 12px;
      
      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
      }
      
      .class-info {
        display: flex;
        gap: 10px;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }
  
  .class-messages {
    min-height: 300px;
    
    .empty-state {
      padding: 40px 0;
    }
  }
  
  .message-card {
    margin-bottom: 16px;
    transition: all 0.3s ease;
    
    &.warning-message {
      border-left: 3px solid #e6a23c;
    }
    
    &.danger-message {
      border-left: 3px solid #f56c6c;
    }
    
    .message-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .message-title {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .message-from {
          font-weight: 500;
          color: #303133;
        }
      }
      
      .message-actions {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .message-content {
      margin: 16px 0;
      white-space: pre-line;
      color: #606266;
      line-height: 1.6;
    }
    
    .message-problems {
      margin-top: 16px;
      border-top: 1px dashed #ebeef5;
      padding-top: 12px;
      
      .problems-title {
        font-weight: 500;
        margin-bottom: 8px;
        color: #606266;
      }
      
      .problems-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .problem-tag {
          cursor: pointer;
          transition: all 0.2s ease;
          
          &:hover {
            color: #409eff;
            background-color: #ecf5ff;
          }
        }
      }
    }
    
    .task-status {
      margin-top: 16px;
      border-top: 1px dashed #ebeef5;
      padding-top: 12px;
      
      .status-info {
        display: flex;
        align-items: center;
        gap: 12px;
        
        span {
          white-space: nowrap;
          font-weight: 500;
          color: #606266;
        }
        
        .el-progress {
          flex-grow: 1;
        }
      }
    }
  }
}

// 对话框样式
.dialog-footer {
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
